//
//  GoogleVerificationViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/2.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "GoogleVerificationViewController.h"
#import "CheckVersionAlearView.h"
@interface GoogleVerificationViewController ()
@property(nonatomic,strong)UILabel *titleLab;
@property(nonatomic,strong)UILabel *titleLable;
@property(nonatomic,strong)UILabel *gooletitleLable;
@property(nonatomic,strong)UIImageView *QRCodeImg;
@property(nonatomic,strong)UILabel *secretKeyLable;
@property(nonatomic,strong)UILabel *accountNumberLable;
@property(nonatomic,strong)UILabel *bindLable;
@property(nonatomic,strong)UILabel *bindMessage;
@property(nonatomic,strong)UILabel *bindMessage1;
@property(nonatomic,strong)UIButton *bindbutton;
@property(nonatomic,strong)NSString *Google_key;
@end

@implementation GoogleVerificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MainBGCOLOR;
    [self custonUI];
    [self GoogleVeriSecretkey];
}
- (void)GoogleVeriSecretkey
{
    
    WeakSelf
    [self GETWithHost:@"" path:twoStepAuthKey param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            weakSelf.Google_key = responseObject[@"result"][@"secret"];
            weakSelf.secretKeyLable.text = [NSString stringWithFormat:@"%@ %@",Localized(@"Google_key"),weakSelf.Google_key];//充值地址
            [weakSelf createQRcodWithUrl:responseObject[@"result"][@"url"]];/*生成二维码*/
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}
- (void)custonUI
{
    [self.view addSubview:self.titleLab];
    [self.view addSubview:self.titleLable];
    [self.view addSubview:self.gooletitleLable];
    [self.view addSubview:self.QRCodeImg];
    [self.view addSubview:self.accountNumberLable];
    [self.view addSubview:self.secretKeyLable];
    [self.view addSubview:self.bindLable];
    [self.view addSubview:self.bindMessage];
    [self.view addSubview:self.bindMessage1];
    [self.view addSubview:self.bindbutton];
}
-(void)initCopyButton:(CGRect)frame tag:(NSInteger)tag
{
    UIButton * button = [[UIButton alloc] initWithFrame:frame];
    [button setTitleColor:TABTITLECOLOR forState:0];
    button.tag = tag;
    [button addTarget:self action:@selector(copybutton:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:Localized(@"copy") forState:0];
    button.titleLabel.font = AutoBoldFont(12);
    if (tag == 0) {
         button.centerY = _titleLable.centerY;
    }else if (tag == 1)
    {
        button.centerY = _accountNumberLable.centerY;
    }else
    {
       button.centerY = _secretKeyLable.centerY;
    }
    [self.view addSubview:button];
}
- (UILabel *)titleLab
{
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(30), RealValue_W(60), UIScreenWidth - RealValue_W(60), RealValue_W(30))];
        _titleLab.textColor = MAINTITLECOLOR;
        _titleLab.text = Localized(@"Google_downloadTitle");
        _titleLab.font = AutoBoldFont(12);
    }
    return _titleLab;
}
- (UILabel *)titleLable
{
    if (!_titleLable) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(RealValue_W(50), _titleLab.bottom +RealValue_W(40), RealValue_W(12), RealValue_W(12))];
        view.backgroundColor = TABTITLECOLOR;
        KViewRadius(view,  RealValue_W(6));
        [self.view addSubview:view];
        _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(view.right +RealValue_W(10), 0, UIScreenWidth - view.right -RealValue_W(110), RealValue_W(30))];
        _titleLable.textColor = MAINTITLECOLOR1;
        _titleLable.text = Localized(@"Google_downloadTitle_message");
        _titleLable.font = AutoFont(12);
        _titleLable.centerY = view.centerY;
        [self initCopyButton:CGRectMake(_titleLable.right +5, 0, RealValue_W(100), RealValue_W(30)) tag:0];
      
    }
   
   return _titleLable;
}
- (UILabel *)gooletitleLable
{
    if (!_gooletitleLable) {
        _gooletitleLable = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(30), _titleLable.bottom +30, UIScreenWidth -RealValue_W(60), 0)];
        _gooletitleLable.textColor = MAINTITLECOLOR;
        _gooletitleLable.font = AutoBoldFont(12);
         _gooletitleLable.numberOfLines = 0;
       
        _gooletitleLable.attributedText = [EXUnit finderattributedString:Localized(@"Google_Title_message") attributedString:Localized(@"Google_Title_message1") color:MAINTITLECOLOR1 font:AutoFont(11)];
        _gooletitleLable.lineBreakMode = NSLineBreakByTruncatingTail;
        [_gooletitleLable sizeToFit];
        _gooletitleLable.height = _gooletitleLable.height;
    }
    return _gooletitleLable;
}
- (UIImageView *)QRCodeImg
{
    if (!_QRCodeImg) {
        _QRCodeImg = [UIImageView dd_imageViewWithFrame:CGRectMake(0, _gooletitleLable.bottom +RealValue_W(40), RealValue_W(180), RealValue_W(180)) islayer:NO imageStr:nil tapAction:^(UIImageView *image) {
            
        }];
        //1.创建长按手势
        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
        
        //2.开启人机交互
        _QRCodeImg.userInteractionEnabled = YES;
        
        //3.添加手势
        [_QRCodeImg addGestureRecognizer:longTap];
        _QRCodeImg.centerX = self.view.centerX;

    }
    return _QRCodeImg;
}
- (UILabel *)accountNumberLable
{
    if (!_accountNumberLable) {
        _accountNumberLable = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(90*2), _QRCodeImg.bottom +RealValue_W(56), RealValue_W(340), RealValue_W(30))];
        
        _accountNumberLable.textColor = MAINTITLECOLOR;
        _accountNumberLable.font = AutoBoldFont(12);
        _accountNumberLable.text = [NSString stringWithFormat:@"%@: %@",Localized(@"set_Account"),[NSString isEmptyString:[EXUserManager personalData].phone]?[EXUserManager personalData].email:[EXUserManager personalData].phone];
        [self initCopyButton:CGRectMake(_accountNumberLable.right, 0,  RealValue_W(100),  RealValue_W(30)) tag:1];
    }
    return _accountNumberLable;
}
- (UILabel *)secretKeyLable
{
    if (!_secretKeyLable) {
        _secretKeyLable = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(90*2), _accountNumberLable.bottom +RealValue_W(40), RealValue_W(340), RealValue_W(30))];
        
        _secretKeyLable.textColor = MAINTITLECOLOR;
        _secretKeyLable.font = AutoBoldFont(12);
        [self initCopyButton:CGRectMake(_secretKeyLable.right, 0,  RealValue_W(100),  RealValue_W(30)) tag:2];
    }
    return _secretKeyLable;
}
- (UILabel *)bindLable
{
    if (!_bindLable) {
        _bindLable = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(30), _secretKeyLable.bottom+30, UIScreenWidth -RealValue_W(60), 0)];
        _bindLable.textColor = MAINTITLECOLOR;
        _bindLable.font = AutoBoldFont(12);
        _bindLable.numberOfLines = 0;
       
        _bindLable.attributedText = [EXUnit finderattributedString:Localized(@"Google_bindTitle_message") attributedString:Localized(@"Google_bindTitle_message1") color:MAINTITLECOLOR1 font:AutoFont(11)];
        [_bindLable sizeToFit];
        _bindLable.height = _bindLable.height;
    }
    return _bindLable;
}
- (UILabel *)bindMessage
{
    if (!_bindMessage) {
       
        _bindMessage = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(72), _bindLable.bottom + 20, UIScreenWidth  - RealValue_W(122), 0)];
        _bindMessage.textColor = MAINTITLECOLOR1;
        _bindMessage.font = AutoFont(12);
        _bindMessage.numberOfLines = 0;
       
        _bindMessage.text = Localized(@"Google_bindNumberOne_message");
         [_bindMessage sizeToFit];
        _bindMessage.height = _bindMessage.height;
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(RealValue_W(50), 0, RealValue_W(12), RealValue_W(12))];
        view.backgroundColor = TABTITLECOLOR;
        view.centerY = _bindMessage.centerY;
        KViewRadius(view,  RealValue_W(6));
        [self.view addSubview:view];
    }
    return _bindMessage;
}
- (UILabel *)bindMessage1
{
    if (!_bindMessage1) {
        _bindMessage1 = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_W(72), _bindMessage.bottom + RealValue_W(16), UIScreenWidth  - RealValue_W(122), 0)];
        _bindMessage1.textColor = MAINTITLECOLOR1;

        _bindMessage1.font = AutoFont(12);
        _bindMessage1.numberOfLines = 0;

        _bindMessage1.text = Localized(@"Google_bindNumberTwo_message");
        _bindMessage1.lineBreakMode = NSLineBreakByTruncatingTail;
         [_bindMessage1 sizeToFit];
        _bindMessage1.height = _bindMessage1.height;
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(RealValue_W(50), 0, RealValue_W(12), RealValue_W(12))];
        view.backgroundColor = TABTITLECOLOR;
        view.centerY = _bindMessage1.centerY;
        KViewRadius(view,  RealValue_W(6));
        [self.view addSubview:view];
    }

    return _bindMessage1;
}
- (void)copybutton:(UIButton *)button
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
   
   
    if (button.tag ==0) {
         pasteboard.string = @"https://itunes.apple.com/cn/app/google-authenticator/id388497605?mt=8" ;
    }else if (button.tag ==1)
    {
         pasteboard.string = [NSString isEmptyString:[EXUserManager personalData].phone]?[EXUserManager personalData].email:[EXUserManager personalData].phone;
    }else
    {
          pasteboard.string = self.Google_key;
    }
    [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Copy_to_paste") view:self.view];
}
- (UIButton *)bindbutton
{
    if (!_bindbutton) {
        _bindbutton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(RealValue_W(30), UIScreenHeight - RealValue_H(30) - RealValue_W(80) - IPhoneBottom - kStatusBarAndNavigationBarHeight, UIScreenWidth -RealValue_W(60) , RealValue_W(80)) title:Localized(@"Google_bindtouch_message") backgroundColor:TABTITLECOLOR titleColor:WHITECOLOR tapAction:^(UIButton *button) {
            
            [self bindButton:button];
        }];
        _bindbutton.titleLabel.font = AutoBoldFont(15);
    }
    return _bindbutton;
}
#pragma mark 绑定谷歌验证逻辑
- (void)bindButton:(UIButton *)button
{
    [EXUserManager saveGoole:@"1"];
    WeakSelf
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"3";
    aleatView.isBindGoole = YES;
    aleatView.cancelBlock = ^{
        [EXUserManager saveGoole:@"0"];
        [custom dismiss];
    };
    WeakObject(aleatView)
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
        
        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        NSDictionary * param = @{@"two_step_code":weakaleatView.gooldField.text,
                                 @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text};
        
        [weakSelf POSTWithHost:@"" path:twoStep param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [EXUserManager saveGoole:@"1"];
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [[NSNotificationCenter defaultCenter] postNotificationName:SetSecurityNotificationse object:nil];
                [custom dismiss];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else
            {
                [EXUserManager saveGoole:@"0"];
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [EXUserManager saveGoole:@"0"];
            [weakaleatView.okButton stopAnimation];
        }];
        
    }];
}
#pragma mark 长按手势弹出警告视图确认
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture

{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
        
    {

        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_Sure_album") titleStr:Localized(@"Asset_Save_picture") openUrl:@"" confirm:Localized(@"transaction_OK") cancel:Localized(@"transaction_cancel")   state:2 RechargeBlock:^{

            // 保存图片到相册
            UIImageWriteToSavedPhotosAlbum(self.QRCodeImg.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);



        }];

        aleartVC.animationStyle = LXASAnimationDefault;
        [aleartVC showLXAlertView];


        
    }
    
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"";
    
    if(!error) {
        
        message =Localized(@"Asset_Saved_album");
        
       [EXUnit showSVProgressHUD:message];
        
    }else
        
    {
        
        message = [error description];
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"album_message") view:kWindow];
        
    }
    
}
- (void)createQRcodWithUrl:(NSString *)url{
    // 1.创建过滤器
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    
    //    NSString *dataString = @"http://www.520it.com";
    
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    
    CIImage *outputImage = [filter outputImage];
    
    // 5.将CIImage转换成UIImage，并放大显示
    
    self.QRCodeImg.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100];
    
}
/**
 
 * 根据CIImage生成指定大小的UIImage
 
 *
 
 * @param image CIImage
 
 * @param size 图片宽度
 
 */

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size

{
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}
@end
